<template>
  <div class="backup-settings">
    <!-- 备份配置 -->
    <t-card title="备份配置" class="setting-card">
      <t-form :data="formData" :label-width="120" @submit="handleSaveConfig">
        <t-form-item label="自动备份">
          <t-switch v-model="formData.autoBackup" />
        </t-form-item>
        
        <template v-if="formData.autoBackup">
          <t-form-item label="备份频率" name="backupFrequency">
            <t-select v-model="formData.backupFrequency">
              <t-option key="daily" value="daily" label="每天" />
              <t-option key="weekly" value="weekly" label="每周" />
              <t-option key="monthly" value="monthly" label="每月" />
            </t-select>
          </t-form-item>
          
          <t-form-item label="保留备份数" name="keepBackups">
            <t-input-number v-model="formData.keepBackups" :min="1" :max="30" />
          </t-form-item>
          
          <t-form-item label="备份内容" name="backupContent">
            <t-checkbox-group v-model="formData.backupContent">
              <t-checkbox value="database">数据库</t-checkbox>
              <t-checkbox value="uploads">上传文件</t-checkbox>
              <t-checkbox value="settings">系统设置</t-checkbox>
            </t-checkbox-group>
          </t-form-item>
          
          <t-form-item label="备份存储位置" name="backupStorage">
            <t-radio-group v-model="formData.backupStorage">
              <t-radio value="local">本地存储</t-radio>
              <t-radio value="cloud">云存储</t-radio>
            </t-radio-group>
          </t-form-item>
          
          <template v-if="formData.backupStorage === 'cloud'">
            <t-form-item label="云存储提供商" name="cloudProvider">
              <t-select v-model="formData.cloudProvider">
                <t-option key="aliyun" value="aliyun" label="阿里云OSS" />
                <t-option key="tencent" value="tencent" label="腾讯云COS" />
                <t-option key="qiniu" value="qiniu" label="七牛云" />
              </t-select>
            </t-form-item>
            
            <t-form-item label="Access Key" name="cloudAccessKey">
              <t-input v-model="formData.cloudAccessKey" placeholder="请输入Access Key" />
            </t-form-item>
            
            <t-form-item label="Secret Key" name="cloudSecretKey">
              <t-input
                v-model="formData.cloudSecretKey"
                type="password"
                placeholder="请输入Secret Key"
                :password-visible="passwordVisible"
                @password-visible-change="(val: boolean) => passwordVisible = val"
              />
            </t-form-item>
            
            <t-form-item label="Bucket" name="cloudBucket">
              <t-input v-model="formData.cloudBucket" placeholder="请输入Bucket名称" />
            </t-form-item>
            
            <t-form-item label="存储区域" name="cloudRegion">
              <t-input v-model="formData.cloudRegion" placeholder="请输入存储区域" />
            </t-form-item>
          </template>
        </template>
        
        <t-form-item>
          <t-button theme="primary" type="submit" :loading="configLoading">保存配置</t-button>
        </t-form-item>
      </t-form>
    </t-card>
    
    <!-- 手动备份 -->
    <t-card title="手动备份" class="setting-card">
      <t-form :label-width="120">
        <t-form-item label="备份内容">
          <t-checkbox-group v-model="manualBackupContent">
            <t-checkbox value="database">数据库</t-checkbox>
            <t-checkbox value="uploads">上传文件</t-checkbox>
            <t-checkbox value="settings">系统设置</t-checkbox>
          </t-checkbox-group>
        </t-form-item>
        
        <t-form-item label="备份描述">
          <t-input v-model="backupDescription" placeholder="请输入备份描述（可选）" />
        </t-form-item>
        
        <t-form-item>
          <t-button @click="handleManualBackup" :loading="backupLoading">
            <template #icon><t-icon name="file-copy" /></template>
            开始备份
          </t-button>
        </t-form-item>
      </t-form>
    </t-card>
    
    <!-- 备份列表 -->
    <t-card title="备份列表" class="setting-card">
      <t-table :data="backupList" :columns="columns" :loading="tableLoading" stripe>
        <template #backup_size="{ row }">
          {{ formatSize(row.size) }}
        </template>
        
        <template #backup_type="{ row }">
          <t-tag v-if="row.type === 'auto'" theme="primary">自动</t-tag>
          <t-tag v-else-if="row.type === 'manual'" theme="success">手动</t-tag>
        </template>
        
        <template #backup_content="{ row }">
          <t-tag v-if="row.content.includes('database')" style="margin-right: 4px">数据库</t-tag>
          <t-tag v-if="row.content.includes('uploads')" style="margin-right: 4px">上传文件</t-tag>
          <t-tag v-if="row.content.includes('settings')" style="margin-right: 4px">系统设置</t-tag>
        </template>
        
        <template #storage="{ row }">
          <span v-if="row.storage === 'local'">本地存储</span>
          <span v-else-if="row.storage === 'cloud'">云存储</span>
        </template>
        
        <template #operation="slotProps">
          <t-space>
            <t-button variant="text" theme="primary" @click="handleRestore(slotProps.row)">
              <template #icon><t-icon name="refresh" /></template>
              恢复
            </t-button>
            <t-button variant="text" theme="primary" @click="handleDownload(slotProps.row)">
              <template #icon><t-icon name="download" /></template>
              下载
            </t-button>
            <t-button variant="text" theme="danger" @click="handleDelete(slotProps.row)">
              <template #icon><t-icon name="delete" /></template>
              删除
            </t-button>
          </t-space>
        </template>
      </t-table>
      
      <div class="pagination-container">
        <t-pagination
          v-model="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="pagination.total"
          :page-size-options="[10, 20, 50]"
          @change="fetchBackupList"
        />
      </div>
    </t-card>
    
    <!-- 恢复对话框 -->
    <t-dialog
      v-model:visible="restoreDialogVisible"
      header="恢复备份"
      :confirm-btn="{ content: '确认恢复', theme: 'danger', loading: restoreLoading }"
      :cancel-btn="{ content: '取消' }"
      @confirm="confirmRestore"
    >
      <template v-if="selectedBackup">
        <p class="dialog-warning">
          <t-icon name="error-circle-filled" style="color: #e34d59; margin-right: 8px;" />
          警告：此操作将使用所选备份覆盖当前数据，操作不可逆！
        </p>
        <div class="backup-info">
          <p><strong>备份名称：</strong>{{ selectedBackup.name }}</p>
          <p><strong>备份时间：</strong>{{ formatDate(selectedBackup.createdAt) }}</p>
          <p><strong>备份描述：</strong>{{ selectedBackup.description || '无' }}</p>
          <p><strong>备份内容：</strong>
            <t-tag v-if="selectedBackup.content.includes('database')" style="margin-right: 4px">数据库</t-tag>
            <t-tag v-if="selectedBackup.content.includes('uploads')" style="margin-right: 4px">上传文件</t-tag>
            <t-tag v-if="selectedBackup.content.includes('settings')" style="margin-right: 4px">系统设置</t-tag>
          </p>
        </div>
        <t-checkbox v-model="restoreConfirm">我已了解此操作的风险，并已创建新的备份</t-checkbox>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 表单数据
const formData = reactive({
  autoBackup: false,
  backupFrequency: 'daily',
  keepBackups: 7,
  backupContent: ['database', 'settings'],
  backupStorage: 'local',
  cloudProvider: 'aliyun',
  cloudAccessKey: '',
  cloudSecretKey: '',
  cloudBucket: '',
  cloudRegion: ''
})

// 手动备份
const manualBackupContent = ref(['database', 'settings'])
const backupDescription = ref('')

// 加载状态
const configLoading = ref(false)
const backupLoading = ref(false)
const tableLoading = ref(false)
const restoreLoading = ref(false)

// 密码可见状态
const passwordVisible = ref(false)

// 备份列表
interface BackupItem {
  id: string;
  name: string;
  type: 'auto' | 'manual';
  content: string[];
  size: number;
  storage: 'local' | 'cloud';
  createdAt: string;
  description?: string;
}

const backupList = ref<BackupItem[]>([])

// 表格列定义
const columns = [
  { colKey: 'name', title: '备份名称', width: 200 },
  { colKey: 'createdAt', title: '备份时间', width: 180 },
  { colKey: 'backup_type', title: '备份类型', width: 100 },
  { colKey: 'backup_content', title: '备份内容', width: 200 },
  { colKey: 'backup_size', title: '文件大小', width: 100 },
  { colKey: 'storage', title: '存储位置', width: 100 },
  { colKey: 'description', title: '备份描述', width: 200 },
  { colKey: 'operation', title: '操作', width: 200, fixed: 'right' }
]

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 恢复备份
const restoreDialogVisible = ref(false)
const selectedBackup = ref<BackupItem | null>(null)
const restoreConfirm = ref(false)

// 获取备份配置
const fetchBackupConfig = async () => {
  try {
    // 这里应该从API获取数据
    // const { data } = await getBackupConfig()
    
    // 模拟数据
    const data = {
      autoBackup: true,
      backupFrequency: 'daily',
      keepBackups: 7,
      backupContent: ['database', 'settings'],
      backupStorage: 'local',
      cloudProvider: 'aliyun',
      cloudAccessKey: '',
      cloudSecretKey: '',
      cloudBucket: '',
      cloudRegion: ''
    }
    
    // 填充表单数据
    if (data) {
      Object.assign(formData, data)
    }
  } catch (error) {
    console.error('获取备份配置失败', error)
    MessagePlugin.error('获取备份配置失败')
  }
}

// 获取备份列表
const fetchBackupList = async () => {
  tableLoading.value = true
  try {
    // 这里应该从API获取数据
    // const { data } = await getBackupList({
    //   page: pagination.current,
    //   pageSize: pagination.pageSize
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const data = {
      items: [
        {
          id: '1',
          name: 'backup_20230601_120000.zip',
          type: 'auto',
          content: ['database', 'settings'],
          size: 1024 * 1024 * 5, // 5MB
          storage: 'local',
          createdAt: '2023-06-01 12:00:00',
          description: '自动备份'
        },
        {
          id: '2',
          name: 'backup_20230602_120000.zip',
          type: 'auto',
          content: ['database', 'settings'],
          size: 1024 * 1024 * 5.2, // 5.2MB
          storage: 'local',
          createdAt: '2023-06-02 12:00:00',
          description: '自动备份'
        },
        {
          id: '3',
          name: 'manual_backup_20230603.zip',
          type: 'manual',
          content: ['database', 'uploads', 'settings'],
          size: 1024 * 1024 * 15, // 15MB
          storage: 'local',
          createdAt: '2023-06-03 15:30:00',
          description: '上线前备份'
        }
      ],
      total: 3
    }
    
    backupList.value = data.items
    pagination.total = data.total
  } catch (error) {
    console.error('获取备份列表失败', error)
    MessagePlugin.error('获取备份列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 保存配置
const handleSaveConfig = async () => {
  configLoading.value = true
  try {
    // 这里应该调用API保存数据
    // await updateBackupConfig(formData)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('保存配置成功')
  } catch (error) {
    console.error('保存备份配置失败', error)
    MessagePlugin.error('保存备份配置失败')
  } finally {
    configLoading.value = false
  }
}

// 手动备份
const handleManualBackup = async () => {
  if (manualBackupContent.value.length === 0) {
    MessagePlugin.warning('请选择备份内容')
    return
  }
  
  backupLoading.value = true
  try {
    // 这里应该调用API执行备份
    // await createBackup({
    //   content: manualBackupContent.value,
    //   description: backupDescription.value,
    //   type: 'manual'
    // })
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    MessagePlugin.success('备份创建成功')
    fetchBackupList() // 刷新备份列表
    backupDescription.value = '' // 清空描述
  } catch (error) {
    console.error('创建备份失败', error)
    MessagePlugin.error('创建备份失败')
  } finally {
    backupLoading.value = false
  }
}

// 恢复备份
const handleRestore = (backup: BackupItem) => {
  selectedBackup.value = backup
  restoreDialogVisible.value = true
  restoreConfirm.value = false
}

// 确认恢复
const confirmRestore = async () => {
  if (!restoreConfirm.value) {
    MessagePlugin.warning('请确认您了解此操作的风险')
    return
  }
  
  if (!selectedBackup.value) return
  
  restoreLoading.value = true
  try {
    // 这里应该调用API执行恢复
    // await restoreBackup(selectedBackup.value.id)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 5000))
    
    MessagePlugin.success('恢复成功，系统将在5秒后刷新')
    
    // 关闭对话框
    restoreDialogVisible.value = false
    
    // 模拟页面刷新
    setTimeout(() => {
      MessagePlugin.info('页面将刷新以应用恢复的数据')
    }, 5000)
  } catch (error) {
    console.error('恢复备份失败', error)
    MessagePlugin.error('恢复备份失败')
  } finally {
    restoreLoading.value = false
  }
}

// 下载备份
const handleDownload = (backup: BackupItem) => {
  // 这里应该调用API下载备份
  // window.location.href = `/api/backup/download/${backup.id}`
  
  MessagePlugin.info('开始下载备份文件')
}

// 删除备份
const handleDelete = async (backup: BackupItem) => {
  try {
    // 确认删除
    MessagePlugin.confirm({
      content: `确定要删除备份 ${backup.name} 吗？此操作不可逆！`,
      confirmBtn: '确认删除',
      cancelBtn: '取消',
      theme: 'danger',
      onConfirm: async () => {
        // 这里应该调用API删除备份
        // await deleteBackup(backup.id)
        
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        MessagePlugin.success('删除成功')
        fetchBackupList() // 刷新备份列表
      }
    })
  } catch (error) {
    console.error('删除备份失败', error)
    MessagePlugin.error('删除备份失败')
  }
}

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  return dateStr // 简单返回，实际项目中可以使用更复杂的格式化
}

// 初始化
onMounted(() => {
  fetchBackupConfig()
  fetchBackupList()
})
</script>

<style scoped>
.backup-settings {
  padding: 20px 0;
}

.setting-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-warning {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: rgba(227, 77, 89, 0.1);
  border-radius: 4px;
  margin-bottom: 16px;
  color: #e34d59;
}

.backup-info {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.backup-info p {
  margin: 8px 0;
}
</style> 